package org.dftproject.genesis.ui.pages.summary.details;

import org.dftproject.genesis.data.genealogy.Events;
import org.dftproject.genesis.data.genealogy.GenealogyUtils;
import org.dftproject.genesis.data.genealogy.IInstant;
import org.dftproject.genesis.data.genealogy.IRole;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.graphics.Color;

public class ChildrenFigure extends Figure {
	
	protected final Color borderColor = new Color(null, 128, 128, 128);
	protected final Color backgroundColor = ColorConstants.white;
	
	private final FigureListViewer viewer;
	
	public ChildrenFigure() {		
		ToolbarLayout layout = new ToolbarLayout(false);
		layout.setSpacing(10);
		setLayoutManager(layout);
		
		viewer = new FigureListViewer(this);
		viewer.setContentProvider(new IStructuredContentProvider() {

			public Object[] getElements(Object input) {
				return new Object[0];
			}
			
			public void dispose() {
			}

			public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			}

		});
		viewer.setFigureProvider(new IFigureProvider() {

			public IFigure getFigure(Object element) {
				if (element instanceof IRole) {
					IRole role = (IRole) element;
					return new ChildFigure(role);
				}
				return null;
			}

		});
		viewer.setComparator(new ViewerComparator() {

			@Override
			public int compare(Viewer viewer, Object o1, Object o2) {
				if (o1 instanceof IRole && o2 instanceof IRole) {
					IInstant instant1 = (IInstant) GenealogyUtils.getValue(((IRole) o1).getEvent(), Events.instant, IInstant.class);
					IInstant instant2 = (IInstant) GenealogyUtils.getValue(((IRole) o2).getEvent(), Events.instant, IInstant.class);
					if (instant1 != null && instant2 != null) {
						Long millis1 = instant1.getMillis();
						Long millis2 = instant2.getMillis();
						if (millis1 != null && millis2 != null) {
							if (millis1 > millis2)
								return 1;
							if (millis1 < millis2)
								return -1;
						}	
					}				
				}
				return o1.hashCode() - o2.hashCode();
			}

		});
		viewer.setInput(this);
	}

	public void addChild(IRole role) {
		viewer.add(role);
	}

}
